package cn.acmoj.oj.controller;

import cn.acmoj.oj.bean.Contest;
import cn.acmoj.oj.bean.ContestRanklist;
import cn.acmoj.oj.bean.Ranklist;
import cn.acmoj.oj.bean.User;
import cn.acmoj.oj.service.ContestRanklistService;
import cn.acmoj.oj.service.ContestService;
import cn.acmoj.oj.service.ProblemSetService;
import cn.acmoj.oj.service.SolutionService;
import com.google.gson.Gson;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * cn.acmoj.oj.controller
 * Springer
 * 2017-11-22
 */
@Controller
@RequestMapping(value = "contest")
public class ContestRanklistController {

    @Resource
    private ContestService contestService;
    @Resource
    private ContestRanklistService contestRanklistService;
    @Resource
    private ProblemSetService problemSetService;
    @Resource
    private Gson gson;

    @RequestMapping(value = "ranklist", method = RequestMethod.GET)
    public String ranklist(@RequestParam(required = false, defaultValue = "-1") Integer cid,
                           HttpSession session,
                           HttpServletRequest request) {
        if (cid != null && cid == -1) {
            cid = (Integer) session.getAttribute("cid");
        }
        if (cid == null) {
            return "contest/error";
        }
        Contest contest = contestService.getOnce(cid);
        if (contest == null) {
            return "contest/error";
        }
        User user = (User) session.getAttribute("user");

        int num = problemSetService.getContestProblemCount(cid);

        List<Ranklist> list = contestRanklistService.getAll(cid, num, contest.getStart_time());
        int myRank = 0;
        if (user != null) {
            int k = 0;
            for (Ranklist aList : list) {
                if (aList.getNick().charAt(0) != '*') {
                    k++;
                    if (aList.getUser_id().equals(user.getUser_id())) {
                        myRank = k;
                        break;
                    }
                }
            }
        }

        request.setAttribute("myRank", myRank);
        request.setAttribute("contest", contest);
        request.setAttribute("list", list);
        request.setAttribute("num", num);
        return "contest/ranklist";
    }

}
